﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Atmk.WaterMeter.MIS.Base;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.WeiXin;
using Atmk.WaterMeter.MIS.Commons.Interfaces.WeiXin;
using Atmk.WaterMeter.MIS.Entities.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NLog;

namespace Atmk.WaterMeter.MIS.Controllers.Pay
{
    /// <summary>
    /// 微信通知消息接收端
    /// </summary>
    public class Wx_SmallRoutine_NoticeController : BaseApiController
    {
        //private static ILogger<Wx_SmallRoutine_NoticeController> _Logger;
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly IWxPayment _wxPayment;
        private readonly IWxRechargeRecordLogic _wxRechargeRecord;
        private readonly IWxAccountLogic _wxAccountLogic;

        /// <inheritdoc />
        public Wx_SmallRoutine_NoticeController(
            IWxPayment wxPayment,
            IWxAccountLogic wxAccountLogic,
            IWxRechargeRecordLogic wxRechargeRecord,
            ILogger<Wx_SmallRoutine_NoticeController> logger
        )
        {
            _wxAccountLogic = wxAccountLogic;
            _wxRechargeRecord = wxRechargeRecord;
            _wxPayment = wxPayment;
            //_Logger = logger;
        }

        [HttpPost("/api/{X-Version}/pay/wx/pay.action")]
        public async Task<IActionResult> PayAction([FromBody] XElement xml)
        {
            try
            {
                //_logger.Debug("微信回调XML"+ xml.ToString());
                var return_code = xml.Elements("return_code").First().Value;
                //返回结果
                var dic = new Dictionary<string, object>
                {
                    ["return_code"] = return_code,
                    ["return_msg"] = ""
                };
                if (return_code == "SUCCESS")
                {
                    //根据收到的xml 通过linq 转为 后台用的model
                    //exp:var value = xml.Elements("value").First().Value;
                    var appid = xml.Elements("appid").First().Value;
                    var mch_id = xml.Elements("mch_id").First().Value;
                    var nonce_str = xml.Elements("nonce_str").First().Value;
                    var sign = xml.Elements("sign").First().Value;
                    var result_code = xml.Elements("result_code").First().Value;
                    var openid = xml.Elements("openid").First().Value;
                    var total_fee = xml.Elements("total_fee").First().Value;
                    var transaction_id = xml.Elements("transaction_id").First().Value;
                    var out_trade_no = xml.Elements("out_trade_no").First().Value;
                    var time_end = xml.Elements("time_end").First().Value;
                    //_logger.Debug("return_code:"+ return_code);
                    if (return_code == "SUCCESS")
                    {
                        //var res = _wxRechargeRecord.RechargeAccount(openid, out_trade_no);
                        //_logger.Debug("openid:"+ openid);
                        //_logger.Debug("out_trade_no:"+ out_trade_no);
                        using (var _context=new atmk_wmdb_devContext())
                        {
                            var wxSrOrderRecord = _context.WxSrOrderRecords.First(w => w.OpenId == openid
                         && w.OutTradeNo == out_trade_no);
                            wxSrOrderRecord.OrderStatus = 2;

                            var order = new OrderDetail()
                            {
                                Money = wxSrOrderRecord.RefillSum,
                                CostType = 0,                                    //0充值1水表扣费2退费
                                RechargeChannels = "微信充值",      //充值渠道
                                WxMessages= wxSrOrderRecord.OutTradeNo,
                                OwnerId = wxSrOrderRecord.OwnerId,
                                CreateTime = DateTime.Now
                            };
                            _context.OrderDetail.Add(order);
                            int result=_context.SaveChanges();
                            //Console.WriteLine(result>0 ? "数据库充值记录成功" : $"数据库充值记录失败:{result}");
                        }
                    }
                    //Console.WriteLine("pay.action");
                    //Console.WriteLine(xml);
                    return Ok(ToXml(dic));
                }
                dic["return_msg"] = "接收通讯标识为FAIL";
                return Ok(ToXml(dic));
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private string ToXml(Dictionary<string, object> m_values)
        {
            //数据为空时不能转化为xml格式
            if (0 == m_values.Count)
            {
                return "";
            }

            var xml = "<xml>";
            foreach (var pair in m_values)
            {
                //字段值不能为null，会影响后续流程
                if (pair.Value == null)
                {
                    return "";
                }

                if (pair.Value is int)
                {
                    xml += "<" + pair.Key + ">" + pair.Value + "</" + pair.Key + ">";
                }
                else if (pair.Value is string)
                {
                    xml += "<" + pair.Key + ">" + "<![CDATA[" + pair.Value + "]]></" + pair.Key + ">";
                }
                else //除了string和int类型不能含有其他数据类型
                {
                    return "";
                }
            }
            xml += "</xml>";
            return xml;
        }
    }
}